package com.yh.blog.controller.admin;

import com.yh.blog.domain.Users;
import com.yh.blog.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 用户登录控制层
 */
@Controller
@RequestMapping("/admin")
public class UsersController {
    @Resource
    private UsersService usersService;

//    跳转到登录页面
    @GetMapping("")
    public String goLogin(){
        return "admin/login";
    }

//    登录
    @PostMapping("/login")
    public ModelAndView login(String username, String password, HttpSession session, RedirectAttributes redirectAttributes){
        Users user=usersService.login(username, password);
        if(user!=null){
            session.setAttribute("user", user);
            return new ModelAndView("admin/index");
        }else{
            redirectAttributes.addFlashAttribute("messages","用户名或密码错误！");
            return new ModelAndView("redirect:/admin");
        }
    }

//    退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
